package com.gdones.gpt.bus.paytemplate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gdones.common.core.dto.MyResult;
import com.gdones.gpt.bus.docs.dto.GptDocs;
import com.gdones.gpt.bus.gptstaff.dto.Staff;
import com.gdones.gpt.bus.gptstaff.dto.StaffModeGrant;
import com.gdones.gpt.bus.gptstaff.mapper.StaffMapper;
import com.gdones.gpt.bus.gptstaff.mapper.StaffModeGrantMapper;
import com.gdones.gpt.bus.gptstaff.service.IStaffInfoService;
import com.gdones.gpt.bus.gptstaff.service.IStaffModeGrantService;
import com.gdones.gpt.bus.modetemplate.dto.GptTemplate;
import com.gdones.gpt.bus.modetemplate.dto.GptTemplateInfo;
import com.gdones.gpt.bus.modetemplate.mapper.GptTemplateInfoMapper;
import com.gdones.gpt.bus.modetemplate.mapper.GptTemplateMapper;
import com.gdones.gpt.bus.paytemplate.dto.GptPayTemplate;
import com.gdones.gpt.bus.paytemplate.dto.PayTemplateDto;
import com.gdones.gpt.bus.paytemplate.mapper.GptPayTemplateMapper;
import com.gdones.gpt.bus.paytemplate.service.IGptPayTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GaoJingBo
 * @since 2023-06-11
 */
@Service
@Transactional
public class GptPayTemplateServiceImpl extends ServiceImpl<GptPayTemplateMapper, GptPayTemplate> implements IGptPayTemplateService {

    @Autowired
    private GptPayTemplateMapper payTemplateMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private GptTemplateMapper templateMapper;

    @Autowired
    private GptTemplateInfoMapper templateInfoMapper;

    @Resource(name = "staffModeGrantServiceImpl")
    private IStaffModeGrantService staffModeGrantServiceImpl;

    @Resource(name = "staffInfoServiceImpl")
    private IStaffInfoService staffInfoServiceImpl;

    @Autowired
    private StaffModeGrantMapper staffModeGrantMapper;

    @Override
    public MyResult mylist(GptPayTemplate dto) {

        MyResult result = new MyResult();

        List<GptPayTemplate> list = payTemplateMapper.myList(dto);

        result.setData(list);
        result.setMsg("查询成功！");

        return result;
    }

    @Override
    public MyResult getByID(String id) {

        MyResult result = new MyResult();

        GptPayTemplate byId = this.getById(id);

        result.setMsg("查询成功！");
        result.setData(byId);

        return result;
    }

    @Override
    public MyResult add(GptPayTemplate dto) {

        MyResult result = new MyResult();

        boolean save = this.save(dto);
        if(save){
            result.setMsg("添加成功！");
        }else{
            result.setMsg("添加失败！");
            result.setCode("9999");
        }

        return result;
    }

    @Override
    public MyResult update(GptPayTemplate dto) {

        MyResult result = new MyResult();

        boolean save = this.updateById(dto);
        if(save){
            result.setMsg("修改成功！");
        }else{
            result.setMsg("修改失败！");
            result.setCode("9999");
        }

        return result;
    }

    @Override
    public MyResult deletes(String ids) {

        MyResult result = new MyResult();

        List<String> list = Arrays.asList(ids.split(","));

        boolean b = this.removeBatchByIds(list);
        if(b){
            result.setMsg("删除成功！");
        }else{
            result.setMsg("删除失败！");
            result.setCode("9999");
        }

        return result;
    }

    @Override
    public MyResult afterPayToActiveStaff(PayTemplateDto dto) {

        MyResult result = new MyResult();

        // 查询用户信息
        Staff staff = staffMapper.selectById(dto.getStaffID());
        if(staff==null){
            result.setMsg("激活出错：客户ID不存在。");
            result.setCode("9999");
            return result;
        }

        // 查询模板信息
        GptPayTemplate payTemplate = this.getById(dto.getPayTemplateID());
        if(payTemplate==null){
            result.setMsg("激活出错：支付模板不存在。");
            result.setCode("9999");
            return result;
        }

        GptTemplate gptTemplate = templateMapper.selectById(payTemplate.getTemplateID());
        if(gptTemplate==null){
            result.setMsg("激活出错：激活中未找到会员模板信息，请联系管理员！");
            result.setCode("9999");
            return result;
        }

        QueryWrapper<GptTemplateInfo> templateInfoQueryWrapper = new QueryWrapper<>();
        templateInfoQueryWrapper.eq("templateID",payTemplate.getTemplateID());

        List<GptTemplateInfo> templateInfos = templateInfoMapper.selectList(templateInfoQueryWrapper);
        if(templateInfos.size()<=0){
            result.setMsg("激活出错：激活中未找到会员模板明细，请联系管理员！");
            result.setCode("9999");
            return result;
        }

        // 判断激活方法
        if(staff.getStaffStateCode()==null){
            //结束时间
            long l = new Date().getTime() + (TimeUnit.DAYS.toMillis(payTemplate.getVipDayLmit()));
            staff.setVipEndTime(new Date(l));
        }else{
            Integer oldVipCode = Integer.valueOf(staff.getStaffStateCode());
            Integer newVipCode = Integer.valueOf(gptTemplate.getGptVipTypeCode());
            if(oldVipCode>newVipCode){
                result.setMsg("激活出错：您当前会员等级高，而您要激活的会员等级低，请在当前会员到期后再进行激活！");
                result.setCode("9999");
                return result;
            }
            //结束时间
            long l = staff.getVipEndTime().getTime() + (TimeUnit.DAYS.toMillis(payTemplate.getVipDayLmit()));
            staff.setVipEndTime(new Date(l));
        }

        // 4. 修改用户信息
        staff.setStaffStateCode(payTemplate.getGptVipTypeCode());
        staff.setStaffStateName(payTemplate.getGptVipTypeName());

        // 计算时间
        staff.setVipStartTime(new Date());

        staff.setVipIsCanUse("1");

        // 创建授权用户空模板集合
        List<StaffModeGrant> grantList = new LinkedList<>();
        for(GptTemplateInfo templateInfo:templateInfos){
            StaffModeGrant grantOne = new StaffModeGrant();
            grantOne.setModelsID(templateInfo.getModelsID());
            grantOne.setModelsName(templateInfo.getModelsName());
            grantOne.setIsHaveDayLimit(templateInfo.getIsHaveDayLimit());
            grantOne.setDayLimitCount(templateInfo.getDayLimitCount());
            grantOne.setUseLess(templateInfo.getDayLimitCount());
            grantOne.setTemplateID(payTemplate.getTemplateID());
            grantOne.setStaffID(staff.getStaffID());
            grantOne.setModeGrantUseTypeCode(templateInfo.getModeGrantUseTypeCode());
            grantOne.setModeGrantUseTypeName(templateInfo.getModeGrantUseTypeName());
            grantList.add(grantOne);
        }

        // 更新客户信息
        int i = staffMapper.updateById(staff);
        if(i<=0){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMsg("激活出错：在用户激活过程中出错。");
            result.setCode("9999");
            return result;
        }

        // 添加授权信息
        int del = staffModeGrantMapper.realDeleteByStaffID(staff.getStaffID());
        boolean b = staffModeGrantServiceImpl.saveBatch(grantList);
        if(!b){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            result.setMsg("激活出错：在用户激活授权过程中出错。");
            result.setCode("9999");
            return result;
        }

        // 激活成功-日志记录
        staffInfoServiceImpl.logForPayActive(staff.getStaffID(),staff.getUserName(),payTemplate.getName(),payTemplate.getGptVipTypeName(),payTemplate.getVipDayLmit(),payTemplate.getPrice());

        result.setMsg("会员【"+payTemplate.getGptVipTypeName()+"】激活成功，激活【"+payTemplate.getVipDayLmit()+"】天");

        return result;
    }
}
